<template>
  <div>
    <div class="pagination">
      <!-- 上 -->
      <button :disabled="pageNo == 1" @click="$emit('getpageNo', pageNo - 1)">上一页</button>
      <button :class="{ active: pageNo == 1 }" v-if="startAndend.start > 1" @click="$emit('getpageNo', 1)">1</button>
      <!-- 中 -->
      <button v-if="startAndend.start > 2">···</button>
      <button :class="{ active: pageNo == item }" @click="$emit('getpageNo', item)" v-for="(item, i) in startAndend.end" :key="i" v-show="item >= startAndend.start">{{ item }}</button>

      <!-- 下 -->
      <button v-if="startAndend.end < pagtotal - 1">···</button>
      <button :class="{ active: pageNo == pagtotal }" v-if="startAndend.end < pagtotal" @click="$emit('getpageNo', pagtotal)">{{ pagtotal }}</button>
      <button :disabled="pageNo == pagtotal" @click="$emit('getpageNo', pageNo + 1)">下一页</button>

      <button style="margin-left: 30px">共 {{ total }} 条</button>
    </div>
    <div>第{{ pageNo }}页</div>
    <div>多少条{{ pageSize }}页</div>
    <div>总共{{ total }}条</div>
    <div>总共分{{ continues }}页</div>
    <div>start为:{{ startAndend.start }}--------end为:{{ startAndend.end }}</div>
  </div>
</template>

<script>
export default {
  name: 'pagination',
  // 封装的必要四个参数(当前在第?页,一页展示多少条,一共有多少条,分多少页)
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    // 总剩余数据(展示多少页)
    pagtotal() {
      // 总数据条数 / 一页展示多少条
      return Math.ceil(this.total / this.pageSize)
    },
    // 计算出连续页码数开始与结束的数字
    startAndend() {
      const { pageNo, pagtotal, continues } = this
      let start = 0
      let end = 0
      // 分页数 大于 总页数 5 > 4 这种情况下
      if (continues > pagtotal) {
        start = 1
        end = pagtotal
      } else {
        // 正常情况下 3 + 2 / 3 - 2 , 1 ~ 5
        start = pageNo - parseInt(continues / 2)
        end = pageNo + parseInt(continues / 2)
        // 针对 1 or 2
        if (start < 2) {
          start = 1
          end = continues
        }
        // 针对 30 or 31
        if (end > pagtotal) {
          start = pagtotal - continues + 1 // 27
          end = pagtotal
        }
      }
      return { start, end }
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  .active {
    // cursor: not-allowed;
    background-color: #409eff;
    color: #fff;
  }
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }
}
</style>
